package serviceparam

import (
	"context"

	"github.com/micro/go-micro/v2/client"
	"github.com/micro/go-micro/v2/client/selector"
	"github.com/micro/go-micro/v2/registry"
)

//设置registry 的context参数, key 固定为params，在registry的构造函数中获取
func ContextParam(value map[string]string) registry.Option {
	return func(o *registry.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, "params", value)
	}
}

//设置registry 的context参数, key 固定为params，在registry的构造函数中获取
func CallServiceReplace(value string) client.CallOption {
	return func(o *client.CallOptions) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, "service_replace", value)
	}
}

//client call option////////////////////////////////////

//根据ClusterName过滤 service
func WithCallClusterFilter(clusterName string) client.CallOption {

	filter := func(services []*registry.Service) []*registry.Service {
		if 0 >= len(clusterName) {
			//如果clusterName 没有设置， 不进行过滤
			//log.Warn("WithCallClusterFilter but clusterName not set , no filter actually")
			return services
		}

		var filtered []*registry.Service

		for _, service := range services {
			//if service.Version == v {
			var nodes []*registry.Node
			for _, n := range service.Nodes {
				if nil != n.Metadata {
					if clusterName == n.Metadata["cluster"] {
						nodes = append(nodes, n)
					}
				}
			}
			if 0 < len(nodes) {
				newService := &registry.Service{
					Name:      service.Name,
					Version:   service.Version,
					Metadata:  service.Metadata,
					Endpoints: service.Endpoints,
					Nodes:     nodes,
				}
				filtered = append(filtered, newService)
			}
			//}
		}
		//log.Error("Filter Service", zap.Reflect("New Service", filtered))
		return filtered
	}

	return client.WithSelectOption(selector.WithFilter(filter))
}
